package manager;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import pojo.PrisTeam1UserAccount;

import util.HibernateUtil;

public class UserAccountManager {

	public boolean createAndStoreUserAccount(String username, String password,
			String mail) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Query query = session
				.createQuery("from PrisTeam1UserAccount p where p.username like :username");
		query.setString("username", username);
		PrisTeam1UserAccount user = new PrisTeam1UserAccount();
		user.setUsername(username);
		user.setPassword(password);
		user.setMail(mail);
		@SuppressWarnings("unchecked")
		List<PrisTeam1UserAccount> userAccount = query.list();
		session.getTransaction().commit();
		if (userAccount.isEmpty()) {
			try {
				Session session2 = HibernateUtil.getSessionFactory()
						.getCurrentSession();
				session2.beginTransaction();
				session2.save(user);
				session2.getTransaction().commit();
				return true;
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		} else {
			System.out.println("Empty");
			return false;
		}
	}

	public PrisTeam1UserAccount getUserAccount(String username, String password) {
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();

			Criteria crit = session.createCriteria(PrisTeam1UserAccount.class);
			crit.add(Restrictions.like("username", username));
			crit.add(Restrictions.like("password", password));
			PrisTeam1UserAccount p1UserAccount = (PrisTeam1UserAccount) crit
					.uniqueResult();

			session.getTransaction().commit();

			return p1UserAccount;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
